﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using Windows.Networking;

namespace ASCM_WpControlApp
{
    class Server
    {
        private StreamSocket _socket = new StreamSocket();
        private StreamSocketListener _listener = new StreamSocketListener();

        public event OnRequest on_request;
        public delegate void OnRequest(ref  Readings reading);


        Readings reading = new Readings();

        public Server()
        {
            Listen();

        }
        async private void Listen()
        {
            _listener.ConnectionReceived += newConnection;
            await _listener.BindServiceNameAsync("3011");

        }

        void newConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            HandleRequest(args.Socket);
        }

        async private void HandleRequest(StreamSocket socket)
        {
            try
            {
                DataReader dr = new DataReader(socket.InputStream);
                var stringHeader = await dr.LoadAsync(6);

                if (stringHeader == 0)
                {
                    return;
                }


                string msg = dr.ReadString(6);
                if (msg != "pingam")
                    throw new Exception("ping error");
                dr.DetachStream();

                on_request(ref reading);


                string X, Y, Z, T, SUM;
                X = "";
                Y = "";
                Z = "";
                T = "";
                SUM = "";

                #region preveri in obdelaj podatke X,Y,Z,T


                X = reading.X.ToString("000");

                Y = reading.Y.ToString("000");

                Z = reading.Z.ToString("000");

                T = reading.Throttle.ToString("000");

                SUM = reading.CheckSum().ToString("0000");



                #endregion

                string data = String.Format("P{0}:{1}:{2}:{3}:{4}#", X, T, Y, T, SUM);

                if (data.Length > 22)
                    Console.WriteLine("error2");

                DataWriter writer = new DataWriter(socket.OutputStream);
                writer.WriteString(data);

                var ret = await writer.StoreAsync();
                writer.DetachStream();

            }
            catch
            {
                return;
            }
            HandleRequest(socket);
        }






    }
}
